﻿using System;
using System.Text;
using System.Web;
using System.Data;
using System.Xml;
using System.IO;
using System.Collections.Specialized;
using QzEbook.AccessObject;
using QzEbook.Common;
using QzEbook.Common.Emun;
using System.Collections.Generic;
using QzEbook.Common.Delegate;
using System.Web.UI.WebControls;


public partial class module_viewBooks : System.Web.UI.UserControl
{
    public ViewBookLoadedDelegate BindDataFinished;
    public Literal TitleLiteral = null;
    private StringBuilder sb;

    private int currentIndex = 1;
    private int pageSize = Config.PageSize;

    private string orderBy="BDate DESC";
    private string filterAt = String.Empty;
    //默认是选取公有电子书.
    private string defaultFilterString = "BIsVisible<>0 and BAuditing=3";

    private bool showPagination = false;
    private bool isEmpty;

    #region 属性
    public bool ShowPagination
    {
        get { return showPagination; }
        set { showPagination = value; }
    }

    public string OrderBy
    {
        get { return orderBy; }
        set { orderBy = value; }
    }
    public string FilterAt
    {
        get
        {
            SqlStringBuilder sb = new SqlStringBuilder();
            sb.appendAnd(DefaultFilterString);
            sb.appendAnd(filterAt);
            return sb.ToString();
        }
        set
        {
            filterAt = value;
        }
    }
    public string DefaultFilterString
    {
        get { return defaultFilterString; }
        set
        {
            defaultFilterString = value;
        }
    }

    public int PageSize
    {
        get { return pageSize; }
        set { pageSize = value; }
    }
    public bool IsEmpty
    {
        get { return isEmpty; }
        set { isEmpty = value; }
    }
    #endregion

    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            bindData();
        }
    }

    private void bindData()
    {

        ViewBooks books = new ViewBooks();
        
        if (!String.IsNullOrEmpty(Request["Pi"]))
        {
            currentIndex = int.Parse(Request["Pi"]);
        }
        if (!String.IsNullOrEmpty(Request["Type"]))
        {
            SqlStringBuilder sqlsb = new SqlStringBuilder();
            sqlsb.appendAnd(this.filterAt);

            //ViewBookAction action = ViewBookAction.Default;
            switch (Request["Type"])
            {
                case "P":
                    this.orderBy = "BComments DESC";
                    break;
                case "K":
                    this.orderBy = "BHit DESC";
                    break;
                case "B": 
                    sqlsb.appendAnd("BPrice<>0");
                    break;
                case "W":
                    this.orderBy = "BComments DESC,BHit DESC";
                    sqlsb.appendAnd(string.Format("BDate>'{0}'" , DateTime.Now.AddDays(-7)));
                    break;
                case "M":
                    this.orderBy = "BComments DESC,BHit DESC";
                    sqlsb.appendAnd(string.Format("BDate>'{0}'", DateTime.Now.AddDays(-1*DateTime.Now.Day)));
                    break;
                case "N" :
                default:
                    break;
            }
            //这边不能用FilterAt,因为他内部已先加入了一个;
            this.filterAt = sqlsb.ToString();
        }
        

        books.OrderBy = this.OrderBy;
        books.FilterAt = this.FilterAt;
        books.PageSize = PageSize;
        books.PageIndex = currentIndex;

        if (!String.IsNullOrEmpty(Request["Uid"]))
        {
            books.UId = int.Parse(Request["Uid"]);
            books.selectList(ViewBookAction.User);
        }
        else if (!String.IsNullOrEmpty(Request["Cid"]))
        {
            books.OrderBy = "BComments DESC,BHit DESC";
            books.CId = int.Parse(Request["Cid"]);
            books.selectList(ViewBookAction.Category);
        }
        else if (!String.IsNullOrEmpty(Request["Tid"]))
        {
            books.OrderBy = "BComments DESC,BHit DESC";
            books.TId = int.Parse(Request["Tid"]);
            books.selectList(ViewBookAction.Tag);
        }
        else if (!String.IsNullOrEmpty(Request["Key"]))
        {
            books.KeyWord = Request["Key"];
            books.selectList(ViewBookAction.KeyWord);
        }
        else
        {
            books.selectList(ViewBookAction.Default);
        }

        sb = new StringBuilder();
        //标题栏;
        if (this.TitleLiteral != null)
        {
            sb.Append(this.TitleLiteral.Text);
        }
        BookListHtml(books.BookList);
        PaginationHTML("", books);
    }

    /// <summary>
    /// 电子书列表;
    /// </summary>
    private void BookListHtml(List<Book> bookList)
    {
        List<Favorite> favoriteList=null;
        if (SessionManager.LoginUser != null)
        {
            Favorite favorite = new Favorite();
            favorite.UserId = SessionManager.LoginUser.Uid;
            favoriteList=favorite.selectUserFavoriteBookIdList();
        }




        sb.AppendLine("<ul id=\"booklist\" class=\"booklist\">");
        if (bookList.Count > 0)
        {
            foreach (Book book in bookList)
            {
                sb.Append("<li>");

                string query=Request.Url.Query;
                if (query != string.Empty)
                {
                    query=String.Format("{0}&Bid={1}",query,book.BookId);
                }else{
                    query = string.Format("?Bid={0}", book.BookId);
                }
                sb.AppendFormat("<a href='detail.xhtml{0}'>",query);

                string thumb = string.Format("{0}{1}", Config.UserBookSavePath, book.Thumb);
                if (!File.Exists(Server.MapPath(thumb)))
                {
                    thumb = "images/siteIcon/error.gif";
                }

                sb.AppendFormat("<img src='{0}' alt='{1}{2}{3}' /></a>", thumb, book.Title, System.Environment.NewLine, book.PostDate.ToString("yyyy-MM-dd"));
                sb.AppendLine("<ins>");

                if (Request["Cid"] == null)
                {
                    sb.AppendFormat("<dfn>{0} 分类:<a href=\"list.xhtml?Cid={1}\" title=\"{2}\">{2}</a></dfn>", book.PostDate.ToString("yyyy-MM-dd"), book.CategoryId, Category.getName(book.CategoryId));
                }
                else
                {
                    sb.AppendFormat("<dfn>日期: {0}</dfn>", book.PostDate.ToString("yyyy-MM-dd"));
                }

                sb.AppendFormat("<dfn class='tag'><img src=\"images/tags.gif\" alt='标签' />:{0}</dfn>", book.getTagListHTML());
                if (book.isSale)
                {
                    sb.AppendLine("<dfn class='auditing'><img src=\"images/siteIcon/auditing.gif\" alt='收费' /></dfn>");
                }
                else
                {
                    bool has = false;
                    if (SessionManager.LoginUser != null)
                    {
                        foreach (Favorite item in favoriteList)
                        {
                            if (item.BookId == book.BookId)
                            {
                                has = true;
                                break;
                            }
                        }

                        if (has)
                        {
                            sb.AppendFormat("<dfn class='favorite'><a href='favorite.xhtml?Bid={0}&type=del' title='删除收藏'><img src=\"images/siteIcon/note_delete.gif\" alt='点击删除收藏' /></a></dfn>", book.BookId);
                        }
                        else
                        {
                            sb.AppendFormat("<dfn class='favorite'><a href='favorite.xhtml?Bid={0}&type=add' title='收藏此书'><img src=\"images/siteIcon/note_new.gif\" alt='点击收藏此书' /></a></dfn>", book.BookId);
                        }
                    }
                }
                sb.AppendFormat("<acronym>标题:{0}</acronym>", book.Title);
                sb.AppendLine("<cite>");
                if (Request["Uid"] == null)
                {
                    sb.AppendFormat("<a href=\"user.xhtml?Uid={0}\"><img src=\"images/icon_user.gif\" alt=\"查看此用户\" /></a>", book.EditorId);
                }
                sb.AppendFormat("<img src=\"images/Hit.gif\" alt=\"被点击次数\"/>{0}  ", book.Hit);
                sb.AppendFormat("<img src=\"images/comment.gif\" alt=\"留言次数\"/>{0}  ", book.Comments);
                sb.AppendLine("</cite></ins>");

                sb.AppendLine("</li>");
            }
        }
        else
        {
            this.IsEmpty = true;
            sb.Append("<li style=\"color:#f9c; padding:5px;\">提示:此模块没有电子书</li>");
        }
        sb.AppendLine("</ul>");

        //解发数据完成事件;
        if (BindDataFinished != null)
        {
            this.BindDataFinished(this);
        }
    }


    /// <summary>
    /// 分页;
    /// </summary>
    /// <param name="books"></param>
    private void PaginationHTML(string domId, ViewBooks books)
    {
        if (books.Pages > 1 && ShowPagination)
        {

            NameValueCollection list = Request.QueryString;
            string url = "?";
            string namevalue = string.Empty;
            foreach (string item in list.AllKeys)
            {
                namevalue = list[item];
                if (item.ToLower() != "pi")
                {
                    url = string.Format("{0}{1}={2}&", url, item, namevalue);
                }
            }


            sb.AppendFormat("<ul class=\"pagination {0}\">", domId);
            if (currentIndex > 1)
            {
                sb.AppendFormat("<li><a href=\"{0}Pi={1}\" titile=\"上一页\">«  </a></li>", url, currentIndex - 1);
            }

            for (int i = 1; i <= books.Pages; i++)
            {
                if (i == currentIndex)
                {
                    sb.AppendFormat("<li class=\"current\">{0}</li> ", i);
                }
                else
                {
                    sb.AppendFormat("<li><a href=\"{0}Pi={1}\" title=第{0}页>{1}</a></li> ", url, i);
                }
            }

            if (currentIndex < books.Pages)
            {
                sb.AppendFormat("<li><a href=\"{0}Pi={1}\" title=\"下一页\">  »</a></li>", url, currentIndex + 1);
            }
            sb.AppendFormat("<li>{0}/{1}</li> ", currentIndex, books.Pages);
            sb.AppendLine("</ul>");

        }
    }


    /// <summary>
    /// 重写;
    /// </summary>
    /// <param name="writer"></param>
    protected override void Render(System.Web.UI.HtmlTextWriter writer)
    {
        if (sb != null)
        {
            writer.Write(sb.ToString());
        }
        base.Render(writer);
    }
}
